import os
import sys

base_dir = os.path.abspath(os.path.dirname(os.getcwd()))
sys.path.append(base_dir)
sys.path.append("/opt/adp_new/common")
sys.path.append("/opt/adp_new")
sys.path.append(os.path.abspath(os.path.dirname(__file__)))

import time

from configs.get_config_info import env_config
from monitor.redis_pool import OPRedis
from scripts.redis_delete_vm import delete_vm, open_vm
from scripts.scripts_log import get_log

app_log = get_log("redis_pub_sub")
db_no = env_config["redis"].get("courseware_db", 10)
redis_conn = OPRedis(db=db_no)


def event_handler(msg, meg_data):
    if "data" in msg:
        data = msg["data"].decode()
        range_uuid = data.split("_")[0]
        courseware_id = data.split("_")[1]
        chapter_id = data.split("_")[2]
        action = data.split("_")[3]
        if action == "on":
            env_start_time = data.split("_")[4]
            env_end_time = data.split("_")[5]
            try:
                resp = open_vm(
                    range_uuid, courseware_id, chapter_id, env_start_time, env_end_time
                )
                if resp.status_code == 200:
                    app_log.info({"msg": f"open range_uuid:{range_uuid} success"})
                else:
                    app_log.error(
                        {
                            "msg": "open range_uuid:{} failed, Parameter error".format(
                                range_uuid
                            )
                        }
                    )

            except Exception as e:
                app_log.error(
                    {
                        "msg": f"open range_uuid:{range_uuid} failed",
                        "error": str(e),
                    }
                )

        elif action == "off":
            try:
                resp = delete_vm(range_uuid, courseware_id, chapter_id)
                if resp.status_code == 200:
                    app_log.info({"msg": f"delete range_uuid:{range_uuid} success"})
                else:
                    app_log.error(
                        {
                            "msg": "delete range_uuid:{} failed, Parameter error".format(
                                range_uuid
                            )
                        }
                    )
                    set_redis_value(
                        range_uuid + "_" + courseware_id + "_" + chapter_id, 86400, 1
                    )

            except Exception as e:
                app_log.error(
                    {
                        "msg": f"delete range_uuid:{range_uuid} failed",
                        "error": str(e),
                    }
                )
                set_redis_value(
                    range_uuid + "_" + courseware_id + "_" + chapter_id, 86400, 1
                )

    else:
        app_log.error({"error": "msg is not correct"})


def set_redis_value(vm_info, end_time, constant):
    global redis_conn
    try:
        if end_time:
            expire = end_time - int(time.time())
            # redis_info = redis_conn.get_value(vm_info)
            # res = judge_exist(redis_info, vm_info)
            # if res:
            #     redis_conn.del_value(vm_info)
            redis_conn.set_value(vm_info, expire, constant)
        else:
            redis_conn.del_value(vm_info)
    except Exception as e:
        app_log.error({"msg": "Courseware Set Redis Value Error", "error": str(e)})


def judge_exist(redis_info, vm_info):
    if redis_info:
        redis_range_uuid = redis_info.split("_")[0]
        redis_courseware_id = redis_info.split("_")[1]
        redis_chapter_id = redis_info.split("_")[2]
        redis_action = redis_info.split("_")[3]
        range_uuid = vm_info.split("_")[0]
        courseware_id = vm_info.split("_")[1]
        chapter_id = vm_info.split("_")[2]
        action = vm_info.split("_")[3]
        if (
            redis_range_uuid == range_uuid
            and redis_courseware_id == courseware_id
            and redis_chapter_id == chapter_id
            and redis_action == action
        ):
            return True
    return False


if __name__ == "__main__":
    pub_sub = redis_conn.conn.pubsub()
    pub_sub.psubscribe(**{f"__keyevent@{db_no}__:expired": event_handler})
    thread = pub_sub.run_in_thread(sleep_time=0.01)
    # present_time = int(time.time()) + 10
    # set_redis_value(
    #     '17718d6b-0606-40a4-bc1a-77ade0ad8e06_13584_d1320841798648d6bf606e9e553fcbd1_on_1640169076_1640169676',
    #     present_time, 1)
